<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>一级页面</h1>
    <iframe id="iframe" src="http://127.0.0.1:8080" frameborder="0" width="500px" height="500px"></iframe>

    <script>
        let obj = {
            name: '张三',
            age: 18
        }
        let iframe = document.getElementById('iframe')
        iframe.onload = function () {
            try {
                // 序列化对象并验证结果
                const jsonString = JSON.stringify(obj);
                console.log('准备发送的数据:', jsonString);

                // 确保iframe内容窗口存在
                if (this.contentWindow) {
                    this.contentWindow.postMessage(jsonString, 'http://127.0.0.1:8080')
                } else {
                    console.error('iframe内容窗口不存在');
                }
            } catch (error) {
                console.error('序列化数据失败:', error);
            }

            window.onmessage = function (e) {
                // 添加来源验证
                if (e.origin === 'http://127.0.0.1:8080' || e.origin === 'http://localhost:8080') {
                    console.log(`二级页面发送来的消息：${e.data}`)
                } else {
                    console.warn('收到未知来源的消息:', e.origin);
                }
            }
        }
    </script>

</body>

</html>